const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");

const allowedMimetype = ['image/jpeg','jpg', 'jpeg', 'image/png', 'image/bmp','gif','video/x-matroska']

function fileFilter (req, file, cb) {

    // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
    if(allowedMimetype.includes(file.mimetype)){
        //接受这个文件，使用`true`，像这样:
        cb(null, true)
    }else{
        // 拒绝这个文件，使用`false`，像这样:
        cb(new Error('Reject this type of picture'))
    }
    // 如果有问题，你可以总是这样发送一个错误:
    //cb(new Error('I don\'t have a clue!'))
  }

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // const uploadPath = path.resolve(__dirname, "../../../pubilc", "uploads");
    let uploadPath = 'C:\\saveImgs'
    console.log('uploadPath',uploadPath)
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    console.log('++++++++++++++req',req.params);
    const params = req.params
    const timeSamp = Date.now();
    let ext = path.extname(file.originalname);
    if(file.originalname === 'blob' && file.mimetype != 'image/bmp'){
      ext = '.png'
    }else if(file.originalname === 'blob' && file.mimetype == 'image/bmp'){
      ext = '.png'
    }else if(!ext && file.mimetype == 'image/png'){
      ext = '.png'
    }
    cb(null, `${params.id}-${params.pos}-${timeSamp}${ext}`);
  },
});

const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 10 } ,fileFilter});

router.post("/:params", upload.single("file"), (req, res, next) => {
  try{
    ResponseHelper.sendData(`保存成功！`, res); 
  }catch(err){
    ResponseHelper.sendErr(err, res);
  }
});

module.exports = router;
